﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AvantGameMachine.DataManagement;
using System.Threading;

namespace AvantGameMachine.Graphics.InternalObjects
{
    public class BackgroundLoader : IRenderizableObject
    {
        private Address addresToLoad = null;
        private ulong dataSize = 0;
        private Thread loadThread = null;

        public BackgroundLoader()
        {
        }

        public virtual void LoadBasic()
        {
        }

        public void SetAddress2Load(Address _address)
        {
            addresToLoad = _address;
        }

        public virtual void Start()
        {
            // First, calculate the number of bytes to load.
            dataSize = AGMPlatform.FSManager.GetDirectorySize(addresToLoad);
            loadThread = new Thread(this.DoLoadFiles);
            loadThread.Start();
        }

        protected override void PrivateUpdate()
        {
            base.PrivateUpdate();
            AGMPlatform.DVars.SetVar("dataSize", dataSize.ToString());
            AGMPlatform.DVars.SetVar("bRead", AGMPlatform.FSManager.TotalRead.ToString());
        }

        private void DoLoadFiles()
        {
            AGMPlatform.FSManager.DoLoadDataFromDirectory(addresToLoad);
        }

        internal void WaitForFinish()
        {
            if (loadThread != null)
            {
                if (loadThread.IsAlive)
                {
                    loadThread.Join();
                }
            }
        }

        internal bool IsLoadingFinish
        {
            get
            {
                if (loadThread != null)
                {
                    return !loadThread.IsAlive;
                }
                return true;
            }
        }
    }
}
